import View from './k-router-view'
import Link from './k-router-link'

// 保存构造函数的引用，避免import
let Vue
class KRouter {
  constructor(options) {
    this.$options = options

    // 如何实现响应式刷新组件， 设置一个响应式数据，根据响应式数据去重新渲染组件
    // Vue.util.defineReactive(this, 'current', '/')
    this.current = window.location.hash.slice(1) || '/'
    Vue.util.defineReactive(this, 'matched', [])

    // match方法可以递归遍历路由表，获得匹配关系
    this.match()

    // 监控url变化
    window.addEventListener('hashchange', this.onHashChange.bind(this))
    window.addEventListener('load', this.onHashChange.bind(this))

    // 创建一个路由映射表(防止路由每次遍历，优化性能)
    // this.routeMap = {}
    // options.routes.forEach(route => {
    //   this.routeMap[route.path] = route
    // })
  }
  
  onHashChange() {
    this.current = window.location.hash.slice(1)
    this.matched = []
    this.match()
  }

  match(routes) {
    routes = routes || this.$options.routes
    // 递归遍历
    for (const route of routes) {
      if (route.path === '/' && this.current === '/') {
        // 完全匹配首页
        this.matched.push(route)
        return 
      }
      if (route.path !== '/' && this.current.indexOf(route.path) != -1) {
        this.matched.push(route)
        if (route.children) {
          this.match(route.children)
        }
        return 
      }
    }
  }

  push (route) {
    if (Object.prototype.toString.call(route) === '[object String]') {
      // 字符串
      window.location.href="/#/" + route
    } else if (Object.prototype.toString.call(route) === "[object Object]") {
      // 对象
    } else {
      console.error('params is not string or object')
    }
  }
}

// vue 安装插件
KRouter.install =  (_Vue) => {
  Vue = _Vue
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router
        // Vue.prototype.$route = this.$route
      }
      console.log('this.$options', this.$options)
    }
  })

  Vue.component('router-link', Link)

  Vue.component('router-view', View)
}

export default KRouter
     